package com.mallcloud.mall.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mallcloud.mall.product.api.dto.SpuTagDTO;
import com.mallcloud.mall.product.api.dto.SpuTagReferenceDTO;
import com.mallcloud.mall.product.api.entity.SpuTagReferenceModel;
import com.mallcloud.mall.product.api.vo.SpuTagReferenceVO;
import com.mallcloud.mall.product.mapper.SpuTagReferenceMapper;
import com.mallcloud.mall.product.service.SpuTagReferenceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 商品分组标签关联信息
 */
@Service
public class SpuTagReferenceServiceImpl extends ServiceImpl<SpuTagReferenceMapper, SpuTagReferenceModel> implements SpuTagReferenceService {

    @Override
    public List<SpuTagReferenceVO> referenceSpu(SpuTagDTO dto) {
        return this.baseMapper.referenceSpu(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateSpuTagReference(SpuTagReferenceDTO dto) {
        int index = 1;
        List<SpuTagReferenceModel> spuTagReferenceModels = new ArrayList<>();
        for (Long spuId : dto.getSpuIds()) {
            SpuTagReferenceModel m = new SpuTagReferenceModel();
            m.setSpuId(spuId);
            m.setTagId(dto.getTagId());
            m.setStatus(true);
            m.setSortOrder(index);
            spuTagReferenceModels.add(m);
            index++;
        }
        this.remove(Wrappers.<SpuTagReferenceModel>lambdaQuery()
                .eq(SpuTagReferenceModel::getTagId, dto.getTagId())
        );
        if(!spuTagReferenceModels.isEmpty()){
            spuTagReferenceModels.forEach(this::save);
        }
        return Boolean.TRUE;
    }
}
